﻿using System;
using System.Linq;
using System.Data.Objects;
using System.Windows.Forms;
using System.Collections.Generic;
using UtfprLibrary.ComponentModel.Security;
using UtfprLibrary.Windows.Forms.ComponentModel.Security;

namespace UtfprLibrary.Windows.Forms.ComponentModel {
    internal partial class UtfprFormModulesRestrictionEditor : Form {
        #region TODO

        private List<IUtfprKeyName> modules = null;
        private ObjectContext context = null;

        private object _value = null;
        public object Value { 
            get { return _value; } 
        }

        public UtfprFormModulesRestrictionEditor(ObjectContext context) {
            InitializeComponent();
            this.context = context;
        }

        #region Event Handlers

        private void UtfprFormRestrictionEditor_Load(object sender, EventArgs e) {
            try {
                populate();
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnOk_Click(object sender, System.EventArgs e) {
            _value = _bsUtfprModule.Current;
        }

        private void btnCancel_Click(object sender, System.EventArgs e) {
            _value = null;
        }

        #endregion

        private List<IUtfprKeyName> getModules() {
            var modules = new List<IUtfprKeyName>();

            foreach (var moduleKey in context.ExecuteStoreQuery<int>("SELECT id FROM tb_seg_sistema_modulo", null).ToList()) {
                modules.Add(new UtfprKeyNameByDesign(moduleKey, context.ExecuteStoreQuery<string>("SELECT descricao FROM tb_seg_sistema_modulo WHERE id = :p0", moduleKey).SingleOrDefault()));
            }

            return modules;
        }

        private void populate() {
            modules = getModules();
            _bsUtfprModule.DataSource = modules.ToList();
        }

        #endregion
    }
}